package extrator.views;

import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import javax.xml.parsers.ParserConfigurationException;

import extrator.Activator;
import gui.main;

import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.part.*;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.viewers.*;
import org.eclipse.swt.graphics.Image;
import org.eclipse.jface.action.*;
import org.eclipse.ui.*;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.SWT;
import org.xml.sax.SAXException;




/**
 * This sample class demonstrates how to plug-in a new
 * workbench view. The view shows data obtained from the
 * model. The sample creates a dummy model on the fly,
 * but a real implementation would connect to the model
 * available either in this or another plug-in (e.g. the workspace).
 * The view is connected to the model using a content provider.
 * <p>
 * The view uses a label provider to define how model
 * objects should be presented in the view. Each
 * view can present the same model objects using
 * different labels and icons, if needed. Alternatively,
 * a single label provider can be shared between views
 * in order to ensure that objects of the same type are
 * presented in the same way everywhere.
 * <p>
 */

public class XPEWSView extends ViewPart {

	/**
	 * The ID of the view as specified by the extension.
	 */
	public static final String ID = "extrator.views.XPEWSView";

	private TableViewer viewer;
	private Action action1;
	private Action action2;
	private Action doubleClickAction;
	private String arquivoXpews;
	private String pastaProjetoXpews;
	
	/*
	 * The content provider class is responsible for
	 * providing objects to the view. It can wrap
	 * existing objects in adapters or simply return
	 * objects as-is. These objects may be sensitive
	 * to the current input of the view, or ignore
	 * it and always show the same content 
	 * (like Task List, for example).
	 */
	
	class ViewContentProvider implements IStructuredContentProvider {
        public void inputChanged(Viewer v, Object oldInput, Object newInput) {
        }
        
        public void dispose() {
        }
        
        public Object[] getElements(Object parent) {
                return new String[] {};
        }
	}
	class ViewLabelProvider extends LabelProvider implements ITableLabelProvider {
        public String getColumnText(Object obj, int index) {
                return getText(obj);
        }
        
        public Image getColumnImage(Object obj, int index) {
                return getImage(obj);
        }
        
        public Image getImage(Object obj) {
        	int metodoOkOuNao = obj.toString().trim().length();
        	if((obj.toString().length() - metodoOkOuNao) == 5)
        		return getImageDescriptor("ok.ico").createImage();
        	else if((obj.toString().length() - metodoOkOuNao) == 6)
        		return getImageDescriptor("no.ico").createImage();
        	else if(obj.toString().startsWith("ns"))
        		return PlatformUI.getWorkbench().
                                getSharedImages().getImage(ISharedImages.IMG_OBJ_FOLDER);
        	else
        		return getImageDescriptor("none.ico").createImage();
        }
	}
	class NameSorter extends ViewerSorter {
	}

	/**
	 * The constructor.
	 */
	public XPEWSView() {
	}

	public TableViewer getTableViewer(){
		return viewer;
	}
	
	public Action getAction1(){
		return action1;
	}
	
	public Action getAction2(){
		return action2;
	}
	
	public void setArquivoXpews(String arquivoXpews){
		this.arquivoXpews = arquivoXpews;
	}
	
	public String getArquivoXpews(){
		return arquivoXpews;
	}
	
	/**
	 * This is a callback that will allow us
	 * to create the viewer and initialize it.
	 */
	public void createPartControl(Composite parent) {
		viewer = new TableViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
		viewer.setContentProvider(new ViewContentProvider());
		viewer.setLabelProvider(new ViewLabelProvider());
		//viewer.setSorter(new NameSorter());
		viewer.setInput(getViewSite());
		makeActions();
		hookContextMenu();
		hookDoubleClickAction();
		contributeToActionBars();
	}

	private void hookContextMenu() {
		MenuManager menuMgr = new MenuManager("#PopupMenu");
		menuMgr.setRemoveAllWhenShown(true);
		menuMgr.addMenuListener(new IMenuListener() {
			public void menuAboutToShow(IMenuManager manager) {
				XPEWSView.this.fillContextMenu(manager);
			}
		});
		Menu menu = menuMgr.createContextMenu(viewer.getControl());
		viewer.getControl().setMenu(menu);
		getSite().registerContextMenu(menuMgr, viewer);
	}

	private void contributeToActionBars() {
		IActionBars bars = getViewSite().getActionBars();
		fillLocalPullDown(bars.getMenuManager());
		fillLocalToolBar(bars.getToolBarManager());
	}

	private void fillLocalPullDown(IMenuManager manager) {
		manager.add(action1);
		manager.add(new Separator());
		manager.add(action2);
	}

	private void fillContextMenu(IMenuManager manager) {
		manager.add(doubleClickAction);
		manager.add(action1);
		manager.add(action2);
		// Other plug-ins can contribute there actions here
		manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
	}
	
	private void fillLocalToolBar(IToolBarManager manager) {
		manager.add(action1);
		manager.add(action2);
	}

	
	private void makeActions() {
		final main i = new main();
		action1 = new Action() {
			public void run() {
				try {
					i.setArquivo(pegarCaminhoDoArquivo(arquivoXpews));
					i.setPastaProjetoXpews(pastaProjetoXpews + "/");
					viewer.setInput(null);
					viewer.add(i.comparar().toArray());
					ResourcesPlugin.getWorkspace().getRoot().refreshLocal(IResource.DEPTH_INFINITE, null);
					action1.setEnabled(true);
					action2.setEnabled(true);
					doubleClickAction.setEnabled(true);
				} catch (ParserConfigurationException e) {
					e.printStackTrace();
				} catch (SAXException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				} catch (CoreException e) {
					e.printStackTrace();
				}
			}
		};
		action1.setText("Verificar todos Métodos");
		action1.setToolTipText("Verificar todos Métodos");
		action1.setImageDescriptor(getImageDescriptor("ok.ico"));
		action1.setEnabled(false);
		
		action2 = new Action() {
			public void run() {
				viewer.setInput(null);
				viewer.add(i.getComparador().listarOperationsXPEWSEFormatar().toArray());
			}
		};
		action2.setText("Listar Métodos");
		action2.setToolTipText("Listar Métodos");
		action2.setImageDescriptor(getImageDescriptor("list.ico"));
		action2.setEnabled(false);
		
		doubleClickAction = new Action() {
			public void run() {
				ISelection selection = viewer.getSelection();
				Object obj = ((IStructuredSelection)selection).getFirstElement();
				viewer.setInput(null);
				try {
					viewer.add(i.comparar(obj.toString()).toArray());
				} catch (ParserConfigurationException e) {
					e.printStackTrace();
				} catch (SAXException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		};
		doubleClickAction.setText("Verificar este Método");
		doubleClickAction.setEnabled(false);
	}
	
	/*private void capturarEditor(){
		IEditorInput arquivo = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor().getEditorInput();
		PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor().addPropertyListener(new IPropertyListener() {
			
			@Override
			public void propertyChanged(Object source, int propId) {
				System.out.println("Tosco\n" + source.toString());
			}
		});
		arquivoXpews = "[L/" + arquivo.getToolTipText() + "]";
		action1.run();
	}*/
	
	public String pegarCaminhoDoArquivo(String xpews){
		String arquivo = xpews.substring(3, xpews.length() - 1);
		arquivo = arquivo.substring(arquivo.indexOf("/"));
		String nomeDoProjeto = xpews.substring(3, xpews.indexOf("/", 3));
		IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
		for (int i = 0; i < projects.length; i++) {
			if(projects[i].getName().compareToIgnoreCase(nomeDoProjeto) == 0){
				pastaProjetoXpews = projects[i].getLocation().toOSString();
				xpews = pastaProjetoXpews + "/" + arquivo; 
			}
		}
		return xpews;
	}

	private void hookDoubleClickAction() {
		viewer.addDoubleClickListener(new IDoubleClickListener() {
			public void doubleClick(DoubleClickEvent event) {
				doubleClickAction.run();
			}
		});
	}
	
	private ImageDescriptor getImageDescriptor(String relativePath) {
		String iconPath = "icons/";
		try {
			Activator plugin = Activator.getDefault();
			URL installURL = plugin.getDescriptor().getInstallURL();
			URL url = new URL(installURL, iconPath + relativePath);
			return ImageDescriptor.createFromURL(url);
		}
		catch (MalformedURLException e) {
			// should not happen
			return ImageDescriptor.getMissingImageDescriptor();
		}
	}

	/**
	 * Passing the focus request to the viewer's control.
	 */
	public void setFocus() {
		viewer.getControl().setFocus();
	}
}